package com.chenglu.android.cart;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chenglu.android.R;
import com.chenglu.android.bean.TabEvent;
import com.chenglu.android.cart.adapter.CartAdapter;
import com.chenglu.android.cart.adapter.CartManager;
import com.chenglu.android.cart.bean.CartBean;
import com.chenglu.android.cart.bean.CartUpdateBean;
import com.chenglu.android.cart.mvp.contract.CartContract;
import com.chenglu.android.cart.mvp.presenter.CartPresenter;
import com.chenglu.android.common.base.BaseMvpFragment;
import com.chenglu.android.common.utils.LogUtils;
import com.chenglu.android.common.utils.SPUtils;
import com.chenglu.android.common.utils.ToastUtils;
import com.chenglu.android.goodsinfo.infoutils.GoodsInfoUtils;
import com.chenglu.android.mine.login.LoginActivity;
import com.chenglu.android.payment.ComfirmOrderActivity;
import com.chenglu.android.payment.bean.OrderGoodsList;
import com.chenglu.android.store.StoreInfoActivity;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.IdentityHashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author: lyj
 * @Created: by Copyright 2023/3/27 Guangzhou Hongma Technology Co., Ltd. All rights reserved.
 * @Description：购物车
 */
public class CartFragment extends BaseMvpFragment<CartPresenter> implements CartContract.View {


    @BindView(R.id.index_tv)
    TextView indexTv;
    @BindView(R.id.rl_title_back)
    RelativeLayout rlTitleBack;
    @BindView(R.id.index_recyclerview)
    RecyclerView indexRecyclerview;
    @BindView(R.id.btn_to_home)
    TextView btnToHome;
    @BindView(R.id.ll_empty_view)
    LinearLayout llEmptyView;
    @BindView(R.id.cb_cart_all)
    CheckBox cbCartAll;
    @BindView(R.id.tv_cart_all)
    TextView tvCartAll;
    @BindView(R.id.ll_cart_check_all)
    LinearLayout llCartCheckAll;
    @BindView(R.id.tv_cart_sum)
    TextView tvCartSum;
    @BindView(R.id.btn_cart_settleaccounts)
    Button btnCartSettleaccounts;

    @BindView(R.id.ll_cart_all)
    LinearLayout llCartAll;
    @BindView(R.id.iv_bg)
    ImageView ivBg;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    //    private List<CartBean.DataBean> beanList = new ArrayList<>();
    private CartAdapter cartAdapter;
    private String aaccessToken;
    private CartManager manager;
    private boolean isEdit = false;
    private static boolean type;

    public static CartFragment newInstance(boolean b) {
        CartFragment cartFragment = new CartFragment();
        type = b;
        return cartFragment;
    }

    @Override
    protected void initView() {

        mPresenter = new CartPresenter();
        mPresenter.attachView(this);
//        showEmptyView();
        //没登录跳转登录界面
//        if (TextUtils.isEmpty(BaseApplication.i().getRefreshToken())) {
//            getActivity().startActivity(new Intent(getActivity(), LoginActivity.class));
//        }

        initAdapter();
        if (type) {
            btnToHome.setVisibility(View.VISIBLE);
            rlTitleBack.setVisibility(View.VISIBLE);
        } else {
            btnToHome.setVisibility(View.GONE);
            rlTitleBack.setVisibility(View.GONE);
        }


    }

    int mPosition;

    private void initAdapter() {
        manager = new CartManager(this);
        cartAdapter = new CartAdapter(this, R.layout.item_carts, manager.getList());
        indexRecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
        indexRecyclerview.setAdapter(cartAdapter);

        cartAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                mPosition = position;

                switch (view.getId()) {
                    //全选同一项的数据
                    case R.id.cb_cart_seller:
                        checkManager(manager.getList().get(position).getTenantId());
                        LogUtils.d("m=" + mSum);
//                        textView.setText(mSum+"");

                        break;
                    case R.id.tv_cart_sellername:
                        //跳转店铺
                        if (cartAdapter.getData().get(position).getShopsTypeId() == 1) {
                            startActivity(new Intent(mContext, StoreInfoActivity.class)
                                    .putExtra("tenandId", cartAdapter.getData().get(position).getTenantId()));
                            ;
                        } else {
                            //餐饮详情

                        }
                        break;
                    case R.id.tv_cart_settleaccounts:
//                        是否营业中 0-筹备中 1-营业中 2-休息中 3-暂停营业
                        if (cartAdapter.getData().get(position).getIsOpen() == 1) {
                            //跳转确认订单
                            ArrayList<OrderGoodsList.OrderGoodsListData> orderConfirm = manager.getOrderConfirm(cartAdapter.getData().get(position).getTenantId());

                            if (orderConfirm.isEmpty()) {
                                ToastUtils.show("请选择商品");
                                return;
                            } else {
                                Intent intent = new Intent(mContext, ComfirmOrderActivity.class);
                                Bundle bundle = new Bundle();
                                OrderGoodsList orderGoodsList = new OrderGoodsList();
                                orderGoodsList.setOrderGoodsListData(orderConfirm);
                                LogUtils.d("集合的数据" + orderGoodsList.getOrderGoodsDTOList().size());
                                bundle.putSerializable(ComfirmOrderActivity.ORDERGOODSLIST, orderGoodsList);
                                intent.putExtra(ComfirmOrderActivity.ORDERTYPE, cartAdapter.getData().get(position).getShopsTypeId());
                                intent.putExtra(ComfirmOrderActivity.TENANTID, cartAdapter.getData().get(position).getTenantId());
                                intent.putExtra(ComfirmOrderActivity.SHOPSTYPEID, cartAdapter.getData().get(position).getShopsTypeId());
                                intent.putExtras(bundle);
                                mContext.startActivity(intent);

                            }
                        } else {
                            ToastUtils.show("暂停营业中");
                            return;
                        }

                        break;
                }


            }

        });


    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_carts;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(getActivity());
    }


    @Override
    public void onResume() {
        super.onResume();
        if (isLogin) {
            aaccessToken = SPUtils.getString("AaccessToken", "AaccessToken");
            mPresenter.getCart(aaccessToken);
        } else {

            getActivity().startActivity(new Intent(getActivity(), LoginActivity.class));
        }
    }

    private void showToLoginDialog() {

    }


    @OnClick({R.id.rl_title_back, R.id.ll_cart_check_all, R.id.cb_cart_all, R.id.btn_cart_settleaccounts, R.id.btn_to_home
            , R.id.iv_bg, R.id.iv_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_title_back:
            case R.id.iv_back:
                LogUtils.d("dddd点击了回退");
                getActivity().finish();

                break;
            case R.id.ll_cart_check_all:
//                cbCartAll.setChecked(!cbCartAll.isChecked());
//                manager.checkAll(cbCartAll.isChecked());
//                cartAdapter.setNewData(manager.getList());
//                cartAdapter.notifyDataSetChanged();
                break;
            case R.id.cb_cart_all:
//                manager.checkAll(cbCartAll.isChecked());
//                cartAdapter.setNewData(manager.getList());
//                cartAdapter.notifyDataSetChanged();
                break;
            case R.id.btn_cart_settleaccounts:
//                ToastUtils.show("请选择一个商品");

//                ArrayList<String> orderConfirm = manager.getOrderConfirm();
//                if(orderConfirm.size()>0){
//                    Intent intent  = new Intent(getActivity(),ComfirmOrderActivity.class);
//                    intent.putStringArrayListExtra(ComfirmOrderActivity.CARTIDS,orderConfirm);
//                    getActivity().startActivity(intent);
//                }

                //todo   结算
                break;

            case R.id.btn_to_home:
//                ToastUtils.show("ddddddd");
                EventBus.getDefault().post(new TabEvent(0));
                break;
        }
    }

    @Override
    public void onSuccess(CartBean bean) {
        cbCartAll.setChecked(false);
        isEdit = false;
        btnCartSettleaccounts.setVisibility(View.GONE);
        tvCartSum.setText("合计：0.00");
        if (bean.getData().size() == 0) {
            showCartEmptyView();
//            showEmptyView("暂无商品~");
        } else {
            llEmptyView.setVisibility(View.GONE);
            indexRecyclerview.setVisibility(View.VISIBLE);
            llCartAll.setVisibility(View.VISIBLE);
            manager.setList(bean.getData());
            cartAdapter.setNewData(manager.getList());
            cartAdapter.notifyDataSetChanged();
        }

    }

    //空购物车 的view
    private void showCartEmptyView() {
        llEmptyView.setVisibility(View.VISIBLE);
        indexRecyclerview.setVisibility(View.GONE);
        llCartAll.setVisibility(View.GONE);
    }

    @Override
    public void getCartUpadet(CartUpdateBean bean) {

        manager.setCartNum();

        manager.getTotalMoney(manager.tenId, manager.cartId);

        cartAdapter.setNewData(manager.getList());
        cartAdapter.notifyDataSetChanged();

    }

    @Override
    public void getCartRemove(CartUpdateBean bean) {
        ToastUtils.show("删除成功");

        mPresenter.getCart(aaccessToken);

    }

    //token失效或者未登录
    @Override
    public void onError(String bean) {
        isLogin = false;
        showCartEmptyView();
//        showEmptyView("暂无商品~");
//        showToLoginDialog();

    }


    //修改购物车商品     public String tenantId;

    public void cartUpdate(String id, String goodsId, int goodsAmount, String goodsName, String tenantId, int shopsTypeId, int isSpec, int status, String goodsSkuId) {
        manager.cartId = goodsId;
        manager.num = goodsAmount;
        manager.tenId = tenantId;
        JSONObject json = new JSONObject();
        try {
            json.put("id", id);
            json.put("goodsId", goodsId);
            json.put("goodsAmount", goodsAmount);
            json.put("goodsName", goodsName);
            json.put("tenantId", tenantId);
            json.put("shopsTypeId", shopsTypeId);
            json.put("isSpec", isSpec);
            json.put("status", status);

            if (isSpec == 1) {
                json.put("goodsSkuId", goodsSkuId);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        mPresenter.getCartUpadet(aaccessToken, mPresenter.getRequestBody(json));

    }

    //删除商品信息
    public void cartRemove(String ids) {
        mPresenter.getCartRemove(aaccessToken, ids);
    }

    //跳转到 商品详情页面
    public void toGoodDetils(String goodsId, int shopsTypeId) {
        //todo  商品详情页面
        GoodsInfoUtils.goodsInfo(mContext, goodsId, shopsTypeId);
    }

    // 购物车 勾选 管理
    public void checkManager(String id) {
//        manager.setCartCheck2(id);

        manager.setCartCheck(id);
//        cartAdapter.getData().get(mPosition).setTotalPrice(mSum+"");
        cartAdapter.setNewData(manager.getList());
        cartAdapter.notifyDataSetChanged();

    }

    // 购物车 勾选 管理
    public void checkManagerItem(String tenantId, String goodsId) {
        manager.setCartCheck2(tenantId, goodsId);

//        manager.setCartCheck(goodsId);
//        cartAdapter.getData().get(mPosition).setTotalPrice(mSum+"");
        cartAdapter.setNewData(manager.getList());
        cartAdapter.notifyDataSetChanged();

    }


    public void setAllSelect(boolean b) {
        cbCartAll.setChecked(b);

    }

    public String mSum;

    public void setSum(String sum) {
        mSum = sum;
        tvCartSum.setText("合计：" + sum);
    }


}
